<template>
  <div class="map-container">
    <div class="search-bar">
      <el-input 
        v-model="searchKeyword" 
        placeholder="请输入地址搜索" 
        @keyup.enter="searchAddress"
        clearable
      >
        <template #append>
          <el-button icon="el-icon-search" @click="searchAddress"></el-button>
        </template>
      </el-input>
    </div>
    <div id="container"></div>
    <div class="selected-info" v-if="selectedAddress">
      <p>已选择地址: {{ selectedAddress }}</p>
      <p v-if="selectedLocation">经纬度: {{ selectedLocation.longitude }}, {{ selectedLocation.latitude }}</p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, defineEmits } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";

let map = null;
let marker = null;
let placeSearch = null;
let AMapInstance = null; // 添加这行来保存 AMap 实例
const emits = defineEmits(['location-selected']);

// 搜索关键词
const searchKeyword = ref('');

// 选中的地址信息
const selectedAddress = ref('');
const selectedLocation = ref(null);

// 搜索地址
const searchAddress = () => {
  if (!searchKeyword.value) return;
  
  if (!placeSearch) {
    // 初始化地点搜索插件
    AMapInstance.plugin('AMap.PlaceSearch', () => {
      placeSearch = new AMapInstance.PlaceSearch({
        pageSize: 5,
        pageIndex: 1,
        city: "全国", // 搜索范围，全国
        map: map
      });
      
      performSearch();
    });
  } else {
    performSearch();
  }
};

// 执行搜索
const performSearch = () => {
  placeSearch.search(searchKeyword.value, (status, result) => {
    if (status === 'complete' && result.info === 'OK') {
      if (result.poiList && result.poiList.pois && result.poiList.pois.length > 0) {
        const firstPoi = result.poiList.pois[0];
        // 定位到第一个搜索结果
        map.setCenter(firstPoi.location);
        map.setZoom(16);
        
        // 设置标记
        setMarker(firstPoi.location, firstPoi.name);
      }
    } else {
      console.log('未找到相关地点');
    }
  });
};

// 添加一个方法来处理地图点击事件
const handleMapClick = (e) => {
  const lnglat = e.lnglat;
  const position = [lnglat.getLng(), lnglat.getLat()];
  
  // 更新或创建标记
  setMarker(position);
  
  // 获取地址信息
  getAddressByLocation(lnglat.getLng(), lnglat.getLat());
};

// 根据经纬度获取地址信息
const getAddressByLocation = (lng, lat) => {
  const geocoder = new AMapInstance.Geocoder({
    radius: 1000,
    extensions: "all"
  });
  
  geocoder.getAddress([lng, lat], (status, result) => {
    if (status === 'complete' && result.regeocode) {
      const address = result.regeocode.formattedAddress;
      selectedAddress.value = address;
      selectedLocation.value = {
        longitude: lng,
        latitude: lat
      };
      
      // 发送选中的位置信息给父组件
      emits('location-selected', {
        address: address,
        longitude: lng,
        latitude: lat
      });
    }
  });
};

// 设置标记
const setMarker = (position, address = '') => {
  if (!marker) {
    marker = new AMapInstance.Marker({
      position: position,
      map: map,
      draggable: true,
      cursor: 'move'
    });
    
    // 添加拖拽结束事件
    marker.on('dragend', (e) => {
      const pos = e.target.getPosition();
      getAddressByLocation(pos.getLng(), pos.getLat());
    });
  } else {
    marker.setPosition(position);
  }
  
  // 如果提供了地址，则直接使用
  if (address) {
    selectedAddress.value = address;
    selectedLocation.value = {
      longitude: position[0],
      latitude: position[1]
    };
    
    // 发送选中的位置信息给父组件
    emits('location-selected', {
      address: address,
      longitude: position[0],
      latitude: position[1]
    });
  }
};

onMounted(() => {
  window._AMapSecurityConfig = {
    securityJsCode: "582925bf40d6a36f3c0eaf54c936ae59",
  };
  AMapLoader.load({
    key: "bcd30a42f78e4f7aca7422a2c47abacd", // 申请好的Web端开发者Key，首次调用 load 时必填
    version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: ['AMap.Scale', 'AMap.Geocoder', 'AMap.PlaceSearch'] //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
  })
    .then((AMap) => {
      AMapInstance = AMap; // 保存 AMap 实例
      map = new AMap.Map("container", {
        // 设置地图容器id
        viewMode: "3D", // 是否为3D地图模式
        zoom: 11, // 初始化地图级别
        center: [116.397428, 39.90923], // 初始化地图中心点位置
      });
      
      // 添加地图点击事件监听
      map.on('click', handleMapClick);
      
      // 初始化地点搜索插件
      AMap.plugin('AMap.PlaceSearch', () => {
        placeSearch = new AMap.PlaceSearch({
          pageSize: 5,
          pageIndex: 1,
          city: "全国", // 搜索范围，全国
          map: map
        });
      });
    })
    .catch((e) => {
      console.log(e);
    });
});

onUnmounted(() => {
  map?.destroy();
});
</script>

<style scoped>
.map-container {
  position: relative;
  height: 100%;
}

.search-bar {
  position: absolute;
  top: 10px;
  left: 10px;
  right: 10px;
  z-index: 10;
}

#container {
  width: 100%;
  height: 500px;
}

.selected-info {
  padding: 10px;
  background-color: #f5f5f5;
  border-top: 1px solid #ddd;
}
</style>